package com.qf.fmall2202.user.shiro;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.fmall2202.user.entity.Users;
import com.qf.fmall2202.user.service.IUsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class CustomRealm extends AuthorizingRealm {

	@Autowired
	IUsersService iUsersService;

	/**
	 * 获取角色和权限信息
	 *
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals ) {

		return null;

	}


	@Override
	protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authenticationToken ) throws AuthenticationException {

		String username = (String) authenticationToken.getPrincipal();

		//查询用户信息
		Users user = iUsersService.getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername,username));

		//账号不存在
		if(user == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}



		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
		return info;


	}
}
